package com.example.dicos.config;

import cn.dev33.satoken.interceptor.SaRouteInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

@Configuration
@EnableWebMvc
public class SaTokenConfigure implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 的路由拦截器，自定义认证规则
        registry.addInterceptor(new SaRouteInterceptor((req, res, handler) -> {
            //拦截所有请求
            SaRouter.match("/**")
                    .notMatch("/swagger-resources/**", "/webjars/**", "/v2/**",
                            "/swagger-ui.html/**", "/doc.html/**","/druid/datasource.html",
                            "/error", "/favicon.ico")
                    .notMatch("/wx/logo/*") //放行
                    .check(r -> StpUtil.checkLogin());
            // 根据路由划分模块，不同模块不同鉴权
            SaRouter.match("/wx/**", "/wx/logo/*", r -> StpUtil.checkPermission("/wx/product/index"));
            SaRouter.match("/wxRole/**","/wxRole/userRole/*", r -> StpUtil.checkPermission("/wx/read"));
            SaRouter.match("/wxPermission/**", r -> StpUtil.checkPermission("/wx/read"));
            SaRouter.match("/wxRolePermissionRelation/**","/wxRolePermissionRelation/userRole/*", r -> StpUtil.checkPermission("/wx/read"));
            SaRouter.match("/manHour/**","/manHour/hour/*", r -> StpUtil.checkPermission("/wx/read"));

        })).addPathPatterns("/**");
    }

    /**
     * 浏览器请求允许 swagger 通过
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 跨域
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {

        registry.addMapping("/**")
                //放行哪些原始域
                .allowedOrigins("*")
                .allowedHeaders("*")
                // 是否发送Cookie
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH")
                .maxAge(3600);
    }
}

